/** 分组**/
const router = require("koa-router")();
const _ = require("lodash");
/**
 * api {get} /home/app/auth/class 分组列表
 *
 *
 */
router.get("/class", async (ctx, nex) => {
  const user = ctx.user;
  const baas = ctx.baas;

  const data = await BaaS.Models.class
    .query(qb => {
      qb.where("baas_id", "=", baas.id);
      qb.orderBy("id", "desc");
    })
    .fetchAll({
      withRelated: []
    });

  ctx.success(data, "分组列表");
});
/**
 * api {get} /home/app/auth/class/:id 获取单个分组
 *
 * apiParam {Number} id
 *
 */
router.get("/class/:id", async (ctx, nex) => {
  const baas = ctx.baas;
  const { id } = ctx.params;

  const data = await BaaS.Models.class
    .query(qb => {
      qb.where("id", "=", id);
      qb.where("baas_id", "=", baas.id);
    })
    .fetch();

  ctx.success(data, "单个分组信息");
});
/**
 * api {post} /home/app/auth/add/class 新增修改分组
 * 
 * apiParam {
	id: 1,
	name: 'home'
 } 
 * 
 */
router.post("/add/class", async (ctx, nex) => {
  const baas = ctx.baas;
  const { id, name } = ctx.post;

  if (_.isEmpty(_.trim(name))) {
    ctx.error("", "名称不能为空");
    return;
  }

  const data = await BaaS.Models.class
    .query(qb => {
      qb.where("baas_id", "=", baas.id);
      qb.where("name", "=", name);
    })
    .fetch();
  if (data && data.id != id) {
    ctx.error("", "此分组已存在");
    return;
  }

  const result = await BaaS.Models.class
    .forge({
      id: id,
      baas_id: baas.id,
      name: name
    })
    .save();

  // 删除redis缓存
  await BaaS.redis.delAll(
    `baas:*:appid:${baas.appid}:appkey:${baas.appkey}:class:*`
  );

  ctx.success(result, "操作成功");
});
/**
 * api {get} /home/app/auth/del/class/:id 删除分组
 *
 * apiParam {Number} id
 *
 */
router.get("/del/class/:id", async (ctx, nex) => {
  const baas = ctx.baas;
  const { id } = ctx.params;

  const data = await BaaS.Models.class
    .query(qb => {
      qb.where("id", "=", id);
      qb.where("baas_id", "=", baas.id);
    })
    .fetch();
  if (!data) {
    ctx.error("", "参数错误");
    return;
  }

  const result = await BaaS.Models.class
    .forge({
      id: id
    })
    .destroy();

  // 删除redis缓存
  await BaaS.redis.delAll(
    `baas:*:appid:${baas.appid}:appkey:${baas.appkey}:class:*`
  );

  ctx.success(result, "删除分组");
});

module.exports = router;
